<template>
  <!-- eslint-disable-next-line -->
  <!-- eslint-disable -->
  <div class="login-container">
    <div class="login-box">
      <div class="login-text"></div>
      <div class="right_class">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          auto-complete="on"
          label-position="left"
        >
          <div class="title-container">
            <h3 class="title" style="text-align:left;color:black">车管平台</h3>
          </div>
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              style="background:black;color:white"
              ref="username"
              v-model="loginForm.username"
              placeholder="Username"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="Password"
              name="password"
              tabindex="2"
              auto-complete="on"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>

          <el-form-item prop="code" class="item-from">
            <el-col :span="9" style="padding-left:0">
              <el-input
                v-model="loginForm.code"
                name="code"
                placeholder="验证码"
                style="width:200px"
                type="text"
                auto-complete="on"
                @keyup.enter.native="handleLogin"
              />
            </el-col>
            <el-col :span="15">
              <span
                style="width:180px;height:38px;display:block;cursor:pointer;background:black;position: absolute;right: 0;top:5px"
                @click.prevent="changeCode"
              >
                <img style="height:28px;" :src="imgSrc" />
              </span>
            </el-col>
          </el-form-item>
          <div style="width:100%;display:flex;justify-content: space-between;">
            <el-button
              :loading="loading"
              type="primary"
              style="width:40%;margin-bottom:30px;"
              @click.native.prevent="handleLogin"
            >登录</el-button>
            <el-button
              type="primary"
              style="width:40%;margin-bottom:30px;"
              @click.native.prevent="forgetPw"
            >忘记密码</el-button>
          </div>
        </el-form>
      </div>
    </div>
    <el-dialog
      width="700px"
      :close-on-click-modal="false"
      :before-close="closeMsg"
      title="忘记密码"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="180px"
        class="formBox"
      >
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="账户名" prop="username">
              <el-input v-model="temp.username" maxlength="20" style="width:400px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="绑定邮箱" prop="email">
              <el-input v-model="temp.email" style="width:400px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="验证码" prop="code">
              <el-col :span="9" style="padding-left:0">
                <el-input
                  style="width:200px"
                  v-model="temp.code"
                  maxlength="20"
                  @keyup.enter.native="changePassword('dataForm')"
                />
              </el-col>
              <el-col :span="4">
                <span
                  style="width:180px;height:38px;display:block;cursor:pointer;background:black"
                  @click.prevent="changeCode"
                >
                  <img style="height:38px;float:right" :src="imgSrc" />
                </span>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="width:100px" @click="closeMsg() ">取消</el-button>
        <el-button style="width:100px" type="primary" @click="changePassword('dataForm')">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// eslint-disable-next-line
/* eslint-disable */
import * as Utils from "@/utils/index"
const createUniqueString_code = Utils.createUniqueString();
import { createCode, validateImgCode } from "@/api/user";
import { retrievePassword } from "@/api/resetPassword";
export default {
  name: "Login",
  data() {
    // const validateUsername = (rule, value, callback) => {
    //   if (!Utils.validUsername(value)) {
    //     callback(new Error('请输入你的用户名'))
    //   } else {
    //     callback()
    //   }
    // }
    // const validatePassword = (rule, value, callback) => {
    //   if (value.length < 6) {
    //     callback(new Error('请输入你的密码'))
    //   } else {
    //     callback()
    //   }
    // }
    const validateCode = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error("验证码错误"));
      } else {
        callback();
      }
    };

    return {
      loginForm: {
        username: "",
        password: "",
        codeKey: "",
        code: ""
      },
      dialogFormVisible: false,
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名必填" },
        ],
        password: [{ required: true, trigger: "blur", message: "密码必填" }],
        code: [{ required: true, trigger: "blur", validator: validateCode }]
      },
      temp: {
        username: null,
        email: null,
        key: null,
        code: null
      },
      rules: {
        username: [
          { required: true, message: "用户名必填", trigger: "change" }
        ],
        email: [
          { required: true, message: "邮箱地址必填", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        code: [{ required: true, message: "验证码必填", trigger: "blur" }]
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      imgSrc: null
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.changeCode();
  },
  methods: {
    closeMsg() {
      this.dialogFormVisible = false;
      this.changeCode();
    },
    changeCode() {
      this.loginForm.codeKey = this.temp.key = createUniqueString_code;
      this.imgSrc = createCode(
        this.loginForm.codeKey,
        new Date().getTime() + ""
      );
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    checkCode() {
      return new Promise((resolve, reject) => {
        const { codeKey, code } = this.loginForm;
        validateImgCode(codeKey, code).then(r => {
          if (r.data.code === 0) {
            resolve();
          } else {
            this.changeCode(); // 重置验证码
            reject();
            throw new Error("验证码错误");
          }
        });
      });
    },
    login() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("loginByUsername", this.loginForm)
            .then(r => {
              this.$router.push({ path: this.redirect || "/enterPrise" });
            })
            .catch(msg => {
              this.changeCode(); // 重置验证码
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    forgetPw() {
      this.changeCode();
      this.dialogFormVisible = true;
    },
    handleLogin() {
      (async () => {
        await this.checkCode();
        await this.login();
      })();
    },
    changePassword(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const arg = Object.values(this.temp);
          retrievePassword(...arg)
            .then(res => {
              if (res.data.code === 0) {
                this.$notify({
                  title: "密码重置成功",
                  message: "成功",
                  type: "success",
                  duration: 2000
                });
                this.dialogFormVisible = false;
              }
            })
            .catch(() => {
              this.changeCode(); // 重置验证码
            });
        }
      });
    }
  }
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: black;
$cursor: #fff;
.login-text {
  width: 100%;
  height: 100%;
  position: relative;
}
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .right_class .el-input input {
    color: $cursor;
  }
}

.login-container .right_class .el-input input {
  background:black!important;
  color: #fff!important;
}

/* reset element-ui css */
.login-box {
  width: 100%;
  height: 100%;
  position: relative;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  display: -webkit-flex;
  min-height: 500px !important;
  overflow: hidden !important;
}
.login-container {
  /*background: #2d3a4b url("../../assets/logo.png") center center no-repeat;*/
  background: #2d3a4b;
  background-size: cover;
  position: absolute;
  height: 100%;
  width: 100%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  .left_class {
    position: relative;
    width: 80%;
  }
  .right_class .el-input {
    display: inline-block;
    height: 49px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 10px 5px 12px 15px;
      color: $light_gray;
      height: 49px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .right_class .el-form-item {
    // border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .right_class .item-from {
    margin-bottom: 30px;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.login-container {
  min-height: 100%;
  width: 100%;
  // background-color: $bg;
  overflow: hidden;
  .login-form {
    position: relative;
    max-width: 100%;
    padding: 200px 35px 0;
    margin: 90px 0 0 auto;
    overflow: hidden;
    position: absolute;
    left: 0;
    right: 0;
    width: 470px;
    background-color: white;
    height: 100%;
    position: relative !important;
    margin: 0 !important;
    padding: 90px 0 0 auto;
    -webkit-box-sizing: border-box !important;
    box-sizing: border-box !important;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 20px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 5px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
